<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Report_requests extends CI_Controller {

	public $data = array();

	function __construct()
	{
		parent::__construct();

		if( !$this->session->userdata('logged_in') )
			redirect('login');

		$this->load->model('merchant_model');
		$this->load->config('regions');
		$this->load->library('form_validation');
		$this->load->library('curl');
		$this->load->helper('form');
		$this->load->helper('download');
	}

		
	function index( $mid = 0 )
	{
		$mid = (int)$mid;

		if( !$mid )
		{
			redirect('report_requests/merchant');
		}

		//get merchant details
		$merchant_details = $this->merchant_model->get_by_id( $mid );

		if( !count($merchant_details) )
		{
			redirect('report_requests/merchant');
		}

		$this->data['merchant_details'] = $merchant_details;
		$this->data['next_token'] = '';
		$this->data['records'] = array();
		$limit = 50;

		$this->data['report_type'] = '';
		$this->data['status'] = '';
		$this->data['reports'] = $this->config->item('reports');
		$this->data['status_list'] = array(
										'_SUBMITTED_' => 'SUBMITTED',
										'_IN_PROGRESS_' => 'IN_PROGRESS',
										'_DONE_NO_DATA_' => 'DONE_NO_DATA',
										'_CANCELLED_'	=> 'CANCELLED'
										);
		
		$report_count_url = site_url('api/reports/reportRequestCount?KEY='.$merchant_details['merchant_id']);
		$report_list_url = site_url('api/reports/reportRequestList/format/json?MaxCount='.$limit.'&KEY='.$merchant_details['merchant_id']);
		
		if( isset($_POST['next_token']) )
		{
			$report_list_url = site_url('api/reports/reportRequestListByNextToken/format/json?NextToken='.urlencode($_POST['next_token']).'&KEY='.$merchant_details['merchant_id']);
		}
		else
		{
			if( isset($_POST['report_type']) && trim($_POST['report_type']) != '' )
			{
				$report_list_url .= '&ReportTypeList='.$_POST['report_type'];
				$this->data['report_type'] = $_POST['report_type'];
			}
			
			if( isset($_POST['status']) && trim($_POST['status']) != '' )
			{
				$report_list_url .= '&ReportProcessingStatusList='.$_POST['status'];
				$this->data['status'] = $_POST['status'];
			}
			else
			{
				$report_list_url .= '&ReportProcessingStatusList=_SUBMITTED_|_CANCELLED_';
			}
				
		}
		
		//die($report_list_url);
		$count = $this->get_api_data( $report_count_url );

		$result = $this->get_api_data( $report_list_url );
		$result = json_decode($result, TRUE);

		$this->data['count']		= $count;
		
		//echo '<pre>';print_r($result);die;
		if( isset($result['next_token']) )
			$this->data['next_token'] 	= $result['next_token'];
		
		if( isset($result['GetReportRequestListResult']) )
		{
			$result = current($result['GetReportRequestListResult']);

			if( isset($result['ReportRequestInfo']) && is_array($result['ReportRequestInfo']) )
			{
				if(isset($result['ReportRequestInfo'][0]))
					$this->data['records']		= $result['ReportRequestInfo'];
				else
					$this->data['records'][0] = $result['ReportRequestInfo'];
			}
		}
		
		//echo '<pre>';print_r($this->data['records']);

		$this->layout->view('reports/request_list', $this->data);
	}


	function merchant( $type = '')
	{
		$this->data['error'] = '';
	
		//get Merchants List
		$result = $this->merchant_model->get_all();
	
		$this->data['merchants'] = array();
		$this->data['merchants'][''] = 'select';
		foreach ($result['rows'] as $row)
		{
			$this->data['merchants'][$row['id']] = $row['name'];
		}
	
	
		$this->form_validation->set_rules('merchant_id', 'Merchant', 'required');
	
		if($this->form_validation->run())
		{
			$merchant_id = $this->input->post('merchant_id');
	
			if( $type == 'request')
				redirect('request_report/'.$merchant_id);
			else 
				redirect('report_requests/'.$merchant_id);
		}
	
		$this->layout->view('reports/view', $this->data);
	}
	
	function request()
	{
		
		//get Merchants List
		$result = $this->merchant_model->get_all();
		
		$this->data['merchants'] = array();
		$this->data['merchants'][''] = 'select';
		foreach ($result['rows'] as $row)
		{
			$this->data['merchants'][$row['id']] = $row['name'];
		}
		
		$this->data['reports'] = $this->config->item('reports');
		
		$this->data['form'] 			= array('merchant_id' => '','report_type' => '','interval_type'=>'','start_date' => '','end_date' => '','add_replace'=>'replace');
		$this->data['records'] 			= array();
		$this->data['success_message'] 	= '';
		$this->data['error_message'] 	= '';
		
		$form = $this->input->post(NULL, TRUE);
		if( $form )
		 $this->data['form'] = $form;
		
		$this->form_validation->set_rules('merchant_id', 'Merchant', 'trim|required');
		$this->form_validation->set_rules('report_type', 'Report', 'trim|required');
		$this->form_validation->set_rules('interval_type', 'Interval Type', 'trim');
		$this->form_validation->set_rules('add_replace', 'Add or Replace', 'trim');
		
		if($form['start_date'] != '' OR $form['end_date'] != '' )
		{
			$this->form_validation->set_rules('start_date', 'Start Date', 'trim|required');
			$this->form_validation->set_rules('end_date', 'End Date', 'trim|required');
		}
		
		if( $this->form_validation->run() )
		{
			//get merchant details
			$merchant_details = $this->merchant_model->get_by_id( $form['merchant_id'] );
			
			$report_request_url = site_url('api/reports/requestReport/format/json?KEY='.$merchant_details['merchant_id']);
			
			if( $form['report_type'] )
				$report_request_url .= '&ReportType='.urlencode($form['report_type']);
			
			if( $form['start_date']  && $form['end_date'] )
				$report_request_url .= '&StartDate='.urlencode($form['start_date']).'&EndDate='.urlencode($form['end_date']);
			
			//die($report_request_url);
			$result = $this->get_api_data( $report_request_url );
			$result = json_decode($result, TRUE);

			$action_data = array();
			$action_data['merchant_id'] = $merchant_details['merchant_id'];
			$action_data['type']='reports';

			$replac="";

			if( isset($result['RequestReportResult']) )
			{
				
				$form['start_date'] 	= date('Y-m-d H:i',local_to_gmt(strtotime($form['start_date'])));
				$form['end_date'] 		= date('Y-m-d H:i',local_to_gmt(strtotime($form['end_date'])));
				
				$start_date = date('Y-m-d',local_to_gmt(strtotime($form['start_date'])));
				$end_date 	= date('Y-m-d',local_to_gmt(strtotime($form['end_date'])));
				
				
				$result = current($result['RequestReportResult']);
				if( isset($result['ReportRequestInfo']) )
				$this->data['records']		= $result['ReportRequestInfo'];
				
				$this->load->model('reports_model');

				$replace_chk="";

				if($form['add_replace']=='replace')
				{
					$replace_chk = $this->reports_model->check_report_request(array('merchant_id'=>$merchant_details['merchant_id'],'report_type'=>$form['report_type'],'date_interval'=>$form['interval_type'],'from_date'=>$start_date,'to_date'=>$end_date));
					//echo $this->db->last_query();die;
				}

				//insert in to request table
				$insert = array();
				$insert['merchant_id'] 	= $merchant_details['merchant_id'];
				$insert['report_type'] 	= $form['report_type'];
				$insert['date_interval']= $form['interval_type'];
				$insert['from_date'] 	= $form['start_date'];
				$insert['to_date'] 		= $form['end_date'];
				$insert['report_request_id']		= $this->data['records']['ReportRequestId'];
				$insert['report_status']		= $this->data['records']['ReportProcessingStatus'];
				$insert['created_time'] 	= date('Y-m-d H:i',local_to_gmt(time()));

				if(!empty($replace_chk)){
					$this->db->update('reports', $insert,array('id' => $replace_chk['id']));
					$replac = 'replaced';
				}else{
					$this->db->insert('reports', $insert);
				}
								
				$action_data['action']= 'The '.$replac.' '.$form['report_type'].' report requested success from '.$form['start_date'].' to '.$form['end_date'].' and the status is '.$this->data['records']['ReportProcessingStatus'];				
				
				$this->data['success_message']  = "Report requested successfully!. RequestID #".$this->data['records']['ReportRequestId'];
			}
			else 
			{
			    $action_data['action']= 'Failed to request the '.$form['report_type'].' report from '.$form['start_date'].' to '.$form['end_date'];				

				$this->data['error_message']  = "Failed to request the Report.Please try again.";
			}

			//ActionLog
			actionlog($action_data);
		}
		
		$this->layout->view('reports/request_report', $this->data);
	}
		
	
	function get_api_data( $url = '')
	{
		$this->curl->create($url);
        $this->curl->option('SSL_VERIFYPEER', false); // for ssl
        $this->curl->option('RETURNTRANSFER', true);
        $data = $this->curl->execute();
		
        return $data;
        
	}

	

	
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
